package com.gongzhiyun.springboot3test.service.impl;

import com.gongzhiyun.springboot3test.entity.message.TbPraiseMessages;
import com.gongzhiyun.springboot3test.entity.message.TbReplyMessages;
import com.gongzhiyun.springboot3test.entity.user.TbUser;
import com.gongzhiyun.springboot3test.mapper.message.TbPraiseMessagesMapper;
import com.gongzhiyun.springboot3test.mapper.message.TbReplyMessagesMapper;
import com.gongzhiyun.springboot3test.mapper.user.TbUserMapper;
import com.gongzhiyun.springboot3test.service.UserService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.gongzhiyun.springboot3test.base.PageBean;
import com.gongzhiyun.springboot3test.base.R;
import com.gongzhiyun.springboot3test.entity.message.TbMessage;
import com.gongzhiyun.springboot3test.entity.user.AuthInfo;
import com.gongzhiyun.springboot3test.interceptor.AppInterceptor;
import com.gongzhiyun.springboot3test.mapper.message.TbMessageMapper;
import com.gongzhiyun.springboot3test.mapper.user.TbUserExinfoMapper;
import com.gongzhiyun.springboot3test.service.TbMessageService;
import com.gongzhiyun.springboot3test.vo.*;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
@Slf4j
@RequiredArgsConstructor
public class TbMessageServiceImpl implements TbMessageService {
    private final UserService userService;
    private final TbMessageMapper tbMessageMapper;
    private final TbUserExinfoMapper tbUserExinfoMapper;
    private final TbPraiseMessagesMapper tbPraiseMessagesMapper;
    private final TbUserMapper tbUserMapper;
    private final TbReplyMessagesMapper tbReplyMessagesMapper;

    /**
     * 用户发布帖子操作
     *
     * @param message
     * @return
     */
    @Override
    public R<String> addMessage(ParamsQueryMessage message) {
        //获取认证信息
        AuthInfo authInfo = AppInterceptor.get();
        Integer uid = authInfo.getUid();
        if (uid == null) {
            return R.fail("出错了");
        }
        //将传入的数据添加到数据库
        TbMessage tbMessage = new TbMessage();
        tbMessage.setTitle(message.getTitle());
        tbMessage.setUid(uid);
        tbMessage.setInfo(message.getInfo());
        int i = tbMessageMapper.insert(tbMessage);
        if (i != 1) {
            return R.fail("操作失败");
        }
        //更新用户拓展信息
        i = tbUserExinfoMapper.addMessages(uid);
        return i == 1 ? R.ok("发布成功") : R.fail("发布失败");


    }

    /**
     * 查询帖子信息
     *
     * @param message
     * @param pageBean
     * @return
     */
    @Override
    public R<List<QueryMessageData>> queryMessage(ParamsQueryMessage message, PageBean pageBean) {
        //查询并分页所有的帖子信息
        QueryWrapper<TbMessage> tbMessageQueryWrapper = new QueryWrapper<>();
        tbMessageQueryWrapper.like("title", message.getTitle());
        tbMessageQueryWrapper.like("info", message.getInfo());
        //排序查询
        switch (pageBean.getOrder()) {
            case 1:
                tbMessageQueryWrapper.orderByDesc("lastupdate");
            case 2:
                tbMessageQueryWrapper.orderByDesc("praise");
            case 3:
                tbMessageQueryWrapper.orderByDesc("reply");
            case 4:
                tbMessageQueryWrapper.orderByDesc("hits");
            default:
                tbMessageQueryWrapper.orderByDesc("id");
        }
        //执行分页查询
        Page<TbMessage> pages = tbMessageMapper.selectPage(new Page<>(pageBean.getPageNum(), pageBean.getPageSize()), tbMessageQueryWrapper);
        //返回分页参数
        pageBean.setTotal(pages.getTotal());
        pageBean.setPages(pages.getPages());
        //遍历查询所有发帖子的用户信息
        List<QueryMessageData> list = new ArrayList<>();
        for (TbMessage tb : pages.getRecords()) {
            QueryMessageData data = new QueryMessageData();
            data.setMessageExInfo(isInfo(tb));
            data.setUser(userService.queryByIdAll(tb.getUid()).viewData());
            data.setMessage(tb);
            list.add(data);
        }
        R<List<QueryMessageData>> result = R.ok(list);
        result.setPageBean(pageBean);
        return result;

    }

    /**
     * 判断帖子是否是当前用户的，是否当前用户已经点赞
     *
     * @return
     */
    public MessageExInfo isInfo(TbMessage tbMessage) {
        AuthInfo authInfo = AppInterceptor.get();
        Integer uid = authInfo.getUid();
        if (uid == null) {
            return MessageExInfo.instance();
        }
        MessageExInfo messageExInfo = MessageExInfo.instance();
        if (tbMessage.getUid().equals(uid)) {
            messageExInfo.setMine(true);
        }
        QueryWrapper<TbPraiseMessages> qw=new QueryWrapper<>();
        qw.eq("uid",uid);
        qw.eq("mid",tbMessage.getId());
        if (tbPraiseMessagesMapper.selectCount(qw)>0) {
            messageExInfo.setPraised(true);
        }

        return messageExInfo;
    }

    /**
     * 查询指定用户的帖子信息
     *
     * @param uid
     * @param pageBean
     * @return
     */
    @Override
    public R<List<QueryMessageData>> queryMessageByUid(Integer uid, PageBean pageBean) {
        if (uid == null) {
            return R.fail("出错了");
        }
        //添加查询条件
        QueryWrapper<TbMessage> tbMessageQueryWrapper = new QueryWrapper<>();
        tbMessageQueryWrapper.eq("uid", uid);
        //排序查询
        switch (pageBean.getOrder()) {
            case 1:
                tbMessageQueryWrapper.orderByDesc("lastupdate");
            case 2:
                tbMessageQueryWrapper.orderByDesc("praise");
            case 3:
                tbMessageQueryWrapper.orderByDesc("reply");
            case 4:
                tbMessageQueryWrapper.orderByDesc("hits");
            default:
                tbMessageQueryWrapper.orderByDesc("id");
        }

        //执行分页查询
        Page<TbMessage> pages = tbMessageMapper.selectPage(new Page<>(pageBean.getPageNum(), pageBean.getPageSize()), tbMessageQueryWrapper);
        pageBean.setTotal(pages.getTotal());
        pageBean.setPages(pages.getPages());
        //分页完成返回数据
        List<QueryMessageData> list = new ArrayList<>();
        for (TbMessage tb : pages.getRecords()) {
            QueryMessageData data = new QueryMessageData();
            data.setMessageExInfo(MessageExInfo.instance());
            data.setMessage(tb);
            list.add(data);
        }
        R<List<QueryMessageData>> result = R.ok(list);
        result.setPageBean(pageBean);
        return result;


    }

    /**
     * 用户点赞帖子操作
     *
     * @param mid
     * @return
     */
    @Override
    public R<String> praise(Integer mid) {
        //检验点赞的帖子是否存在
        TbMessage tbMessage = tbMessageMapper.selectById(mid);
        if (tbMessage == null) {
            return R.fail("帖子不存在");
        }
        //获取认证信息
        AuthInfo authInfo = AppInterceptor.get();
        Integer uid = authInfo.getUid();
        if (uid == null) {
            return R.fail("出错了");
        }
        //校验用户是否已经点赞
        QueryWrapper<TbPraiseMessages> qw = new QueryWrapper<>();
        qw.eq("uid", uid);
        qw.eq("mid", mid);
        TbPraiseMessages tbPraiseMessages = tbPraiseMessagesMapper.selectOne(qw);
        if (tbPraiseMessages != null) {
            //已经点赞，则取消点赞
            int i = tbMessageMapper.DecPraise(mid);
            if (i != 1) {
                return R.fail("操作失败");
            }
            //删除已经保存的点赞信息
            i = tbPraiseMessagesMapper.deleteById(tbPraiseMessages.getId());
            return i == 1 ? R.ok("点赞成功") : R.fail("点赞失败");
        }
        //未点赞，则保存点赞信息
        tbPraiseMessages = new TbPraiseMessages();
        tbPraiseMessages.setMid(mid);
        tbPraiseMessages.setUid(uid);
        int i = tbPraiseMessagesMapper.insert(tbPraiseMessages);
        if (i != 1) {
            return R.fail("操作失败");
        }
        //增加帖子的点赞数
        i = tbMessageMapper.addPraise(mid);
        return i == 1 ? R.ok("点赞成功") : R.fail("点赞失败");


    }

    /**
     * 删除帖子操作
     *
     * @param del
     * @return
     */
    @Override
    public R<String> delete(ParamsDel del) {
        //校验帖子存不存在
        TbMessage tbMessage = tbMessageMapper.selectById(del.getId());
        if (tbMessage == null) {
            return R.fail("帖子不存在");
        }
        //获取认证信息
        AuthInfo authInfo = AppInterceptor.get();
        Integer uid = authInfo.getUid();
        if (uid == null) {
            return R.fail("出错了");
        }
        //校验是否是管理员操作
        TbUser user = tbUserMapper.selectById(uid);
        if (user.getRole() == 1) {
            //管理员操作,需要删除理由
            if (del.getReason() == null && del.getReason().isEmpty()) {
                return R.fail("请说明删除理由");
            }
            //更新帖子删除理由
            tbMessage.setReason(del.getReason());
            int i = tbMessageMapper.updateById(tbMessage);
            if (i != 1) {
                return R.fail("更新删除理由失败");
            }
            //执行删除操作
            i = tbMessageMapper.deleteById(del.getId());
            if (i != 1) {
                return R.fail("操作失败");
            }
            //删除后需更新用户拓展信息
            i = tbUserExinfoMapper.DecMessages(tbMessage.getUid());
            return i == 1 ? R.ok("删除成功") : R.fail("删除失败");
        }

        //不是管理员操作，只能删除自己发布的帖子
        if (!tbMessage.getUid().equals(uid)) {
            return R.fail("只能操作自己发布的帖子");
        }
        int i = tbMessageMapper.deleteById(tbMessage.getId());
        if (i != 1) {
            return R.fail("操作失败");
        }
        //更新用户拓展信息
        i = tbUserExinfoMapper.DecMessages(uid);
        return i == 1 ? R.ok("删除成功") : R.fail("删除失败");

    }

    /**
     * 查询帖子详细信息
     *
     * @param mid
     * @param pageBean
     * @return
     */
    @Override
    public R<ParamsDetailMessageData> detailMessage(Integer mid, PageBean pageBean) {

        //查询出mid编号的帖子
        TbMessage tbMessage = tbMessageMapper.selectById(mid);
        if (tbMessage == null) {
            return R.fail("帖子不存在");
        }
        //查询出mid编号帖子发布的用户
        UserInfo muser = userService.queryByIdAll(tbMessage.getUid()).viewData();
        //分页查询所有mid帖子的回复信息
        QueryWrapper<TbReplyMessages> qw = new QueryWrapper<>();
        qw.eq("mid", mid);
        //排序查询
        switch (pageBean.getOrder()) {
            case 1:
                qw.orderByDesc("lastupdate");
            case 2:
                qw.orderByDesc("praise");
            default:
                qw.orderByDesc("id");
        }
        //执行分页查询
        Page<TbReplyMessages> pages = tbReplyMessagesMapper.selectPage(new Page<>(pageBean.getPageNum(), pageBean.getPageSize()), qw);
        pageBean.setPages(pages.getPages());
        pageBean.setTotal(pages.getTotal());
        //遍历
        List<ParamsReplyData> list = new ArrayList<>();
        for (TbReplyMessages tb : pages.getRecords()) {
            ParamsReplyData data = new ParamsReplyData();
            data.setTbReplyMessages(tb);
            data.setUser(userService.queryByIdAll(tb.getUid()).viewData());
            list.add(data);
        }
        //返回数据
        ParamsDetailMessageData data = new ParamsDetailMessageData();
        data.setTbMessage(tbMessage);
        data.setExInfo(MessageExInfo.instance());
        data.setUser(muser);
        data.setReplies(list);
        R<ParamsDetailMessageData> r = R.ok(data);
        r.setPageBean(pageBean);

        return r;
    }
}
